import {
  Component,
  OnInit,
  HostBinding,
  ElementRef,
  Input,
  OnDestroy,
  AfterContentInit,
} from '@angular/core';
import { Subscription } from 'rxjs';

import { TableFlexService } from './table-flex.service';
import { TableSelectService } from './table-select.service';
import { TableSelectBase } from './table-select-base';

@Component({
  selector: 'fui-table-row',
  templateUrl: './table-row.component.html',
})
export class TableRowComponent extends TableSelectBase implements OnInit, AfterContentInit, OnDestroy {
  @HostBinding('class.fui-table-row') hostClass = true;

  /** Optional attribute. Required for selection feature. */
  @Input() fuiTableRowDatum: any;

  get selected() {
    return this.tableSelect.getRowSelected(this.fuiTableRowDatum);
  }

  set selected(selected) {
    if (typeof this.fuiTableRowDatum === 'object') {
      this.tableSelect.select(this.fuiTableRowDatum, selected);
    }
  }

  hideSelectSub: Subscription;

  constructor(
    private element: ElementRef,
    private tableFlex: TableFlexService,
    private tableSelect: TableSelectService,
  ) {
    super();
  }

  ngOnInit() {
    this.tableSelect.register(this.fuiTableRowDatum);
    this.hideSelectSub = this.hideSelectObservable.subscribe((hide) => {
      this.tableSelect.muteSelect(this.fuiTableRowDatum, hide);
    });
  }

  ngOnDestroy() {
    this.tableSelect.unregister(this.fuiTableRowDatum);
    this.tableFlex.unregister(this.element.nativeElement);
    this.hideSelectSub.unsubscribe();
  }

  ngAfterContentInit() {
    this.tableFlex.register(this.element.nativeElement);
  }
}
